import permision from "./js/permission.js"
import {
	uploadFile,
	SelectListFile,
	DeleteHandleFile
} from './api.js'
var sourceType = [
	['camera'],
	['album'],
	['camera', 'album']
]
var sizeType = [
	['compressed'],
	['original'],
	['compressed', 'original']
]
export const UploadImgHandle = {
	data() {
		return {
			imageList: [],
			sourceTypeIndex: 2,
			sizeTypeIndex: 2,
			countIndex: 1,
		}
	},
	methods: {
		loadFiles(refId) {
			SelectListFile({
				refId
			}).then(res => {
				this.imageList = res.data.map(d => {
					return {
						id: d.id,
						name: d.name,
						size: d.size,
						status: 1,
						url: d.content
					}
				})
			})
		},
		chooseOneImage(formData) {
			return new Promise(async (resolve) => {
				// #ifdef APP-PLUS
				// TODO 选择相机或相册时 需要弹出actionsheet，目前无法获得是相机还是相册，在失败回调中处理
				if (this.sourceTypeIndex !== 2) {
					let status = await this.checkPermission();
					if (status !== 1) {
						return;
					}
				}
				// #endif
				uni.chooseImage({
					sourceType: ['camera', 'album'],
					sizeType: ['compressed', 'original'],
					count: 1,
					success: (res) => {
						console.log('chooseImage', res)
						// this.imageList = this.imageList.concat(res.tempFilePaths);
						uploadFile({
							filePath: res.tempFilePaths[0],
							formData
						}).then(res => {
							console.log('uploadFile', res)
							resolve(JSON.parse(res))
						})
					},
					fail: (err) => {
						console.log("err: ", err);
						this.chooseImageError(err)
					}
				})
			})
		},
		deleteImage(index) {
			let item = this.imageList[index]
			if (item) {
				if (item.id) {
					DeleteHandleFile({
						id: item.id
					}).then(res => {
						if (res.code === 20000) {
							this.imageList.splice(index, 1)
						}
					})
				}
			}
		},
		async uploadFiles(formData) {
			if (this.imageList.filter(d => d.status == 0)) {
				return await Promise.all(this.imageList.filter(d => d.status == 0).map(d => {
					formData.size = d.size
					formData.name = d.name
					return uploadFile({
						filePath: d.url,
						formData
					}).then(res => {
						console.log('uploadFile', res)
						return true
					}).catch(() => false)
				}))
			}
		},
		chooseImage: async function() {
			// #ifdef APP-PLUS
			// TODO 选择相机或相册时 需要弹出actionsheet，目前无法获得是相机还是相册，在失败回调中处理
			if (this.sourceTypeIndex !== 2) {
				let status = await this.checkPermission();
				if (status !== 1) {
					return;
				}
			}
			// #endif

			if (this.imageList.length === this.countIndex) {
				let isContinue = await this.isFullImg();
				console.log("是否继续?", isContinue);
				if (!isContinue) {
					return;
				}
			}
			uni.chooseImage({
				sourceType: sourceType[this.sourceTypeIndex],
				sizeType: sizeType[this.sizeTypeIndex],
				count: this.countIndex - this.imageList.length,
				success: (res) => {
					console.log('res.tempFilePaths', res)
					this.imageList = this.imageList.concat(res.tempFiles.map(d => {
						return {
							name: d.name,
							size: d.size,
							status: 0,
							url: d.path
						}
					}))
					// this.imageList = this.imageList.concat(res.tempFilePaths);
				},
				fail: (err) => {
					console.log("err: ", err);
					this.chooseImageError(err)
				}
			})
		},
		chooseImageError(err) {
			// #ifdef APP-PLUS
			if (err['code'] && err.code !== 0 && this.sourceTypeIndex === 2) {
				this.checkPermission(err.code);
			}
			// #endif
			// #ifdef MP
			if (err.errMsg.indexOf('cancel') !== '-1') {
				return;
			}
			uni.getSetting({
				success: (res) => {
					let authStatus = false;
					switch (this.sourceTypeIndex) {
						case 0:
							authStatus = res.authSetting['scope.camera'];
							break;
						case 1:
							authStatus = res.authSetting['scope.album'];
							break;
						case 2:
							authStatus = res.authSetting['scope.album'] && res
								.authSetting['scope.camera'];
							break;
						default:
							break;
					}
					if (!authStatus) {
						uni.showModal({
							title: '授权失败',
							content: '应用需要从您的相机或相册获取图片，请在设置界面打开相关权限',
							success: (res) => {
								if (res.confirm) {
									uni.openSetting()
								}
							}
						})
					}
				}
			})
			// #endif
		},
		isFullImg: function() {
			return new Promise((res) => {
				uni.showModal({
					content: "已经有9张图片了,是否清空现有图片？",
					success: (e) => {
						if (e.confirm) {
							this.imageList = [];
							res(true);
						} else {
							res(false)
						}
					},
					fail: () => {
						res(false)
					}
				})
			})
		},
		previewImage: function(e) {
			var current = e.target.dataset.src
			uni.previewImage({
				current: current,
				urls: this.imageList.map(d => d.url)
			})
		},
		async checkPermission(code) {
			let type = code ? code - 1 : this.sourceTypeIndex;
			let status = permision.isIOS ? await permision.requestIOS(sourceType[type][0]) :
				await permision.requestAndroid(type === 0 ? 'android.permission.CAMERA' :
					'android.permission.READ_EXTERNAL_STORAGE');

			if (status === null || status === 1) {
				status = 1;
			} else {
				uni.showModal({
					content: "没有开启权限",
					confirmText: "设置",
					success: function(res) {
						if (res.confirm) {
							permision.gotoAppSetting();
						}
					}
				})
			}

			return status;
		}
	}
}